package org.jix.gbook.kv.biz.service.impl;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.jix.framework.common.exception.BizException;
import org.jix.framework.common.response.Response;
import org.jix.gbook.kv.biz.domain.dataObject.NoteContentDO;
import org.jix.gbook.kv.biz.domain.repository.NoteContentRepository;
import org.jix.gbook.kv.biz.enums.ResponseCodeEnum;
import org.jix.gbook.kv.biz.service.NoteContentService;
import org.jix.gbook.kv.dto.req.AddNoteContentReqDTO;
import org.jix.gbook.kv.dto.req.DeleteNoteContentReqDTO;
import org.jix.gbook.kv.dto.req.FindNoteContentReqDTO;
import org.jix.gbook.kv.dto.resp.FindNoteContentRespDTO;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.UUID;

/**
 * @author stark
 * @date 2025/7/21 16:07
 * @description 笔记内容存储业务实现类
 **/
@Service
@Slf4j
public class NoteContentServiceImpl implements NoteContentService {

    @Resource
    private NoteContentRepository noteContentRepository;

    /**
     * 添加笔记内容
     * @param addNoteContentReqDTO
     * @return
     */
    @Override
    public Response<?> addNoteContent(AddNoteContentReqDTO addNoteContentReqDTO) {
        //笔记ID
        String uuid = addNoteContentReqDTO.getUuid();
        //笔记内容
        String content = addNoteContentReqDTO.getContent();

        //构建数据库DTO实体类
        NoteContentDO noteContentDO = NoteContentDO.builder()
                .id(UUID.fromString(uuid)) //todo 暂时随机，后续改成noteID
                .content(content)
                .build();

        //插入数据
        noteContentRepository.save(noteContentDO);
        return Response.success();
    }

    /**
     * 查询笔记内容
     * @param findNoteContentReqDTO
     * @return
     */
    @Override
    public Response<FindNoteContentRespDTO> findNoteContent(FindNoteContentReqDTO findNoteContentReqDTO) {
        //笔记ID
        String uuid = findNoteContentReqDTO.getUuid();
        //根据ID查询内容
        Optional<NoteContentDO> optional = noteContentRepository.findById(UUID.fromString(uuid));

        //笔记内容不存在
        if (!optional.isPresent()) {
            throw new BizException(ResponseCodeEnum.NOTE_CONTENT_NOT_FOUND);
        }

        NoteContentDO noteContentDO = optional.get();
        //构建反参
        FindNoteContentRespDTO findNoteContentRespDTO = FindNoteContentRespDTO.builder()
                .uuid(noteContentDO.getId())
                .content(noteContentDO.getContent())
                .build();

        return Response.success(findNoteContentRespDTO);
    }

    /**
     * 删除笔记内容
     * @param deleteNoteContentReqDTO
     * @return
     */
    @Override
    public Response<?> deleteNoteContent(DeleteNoteContentReqDTO deleteNoteContentReqDTO) {
        //笔记id
        String noteId = deleteNoteContentReqDTO.getUuid();
        //删除笔记内容
        noteContentRepository.deleteById(UUID.fromString(noteId));

        return Response.success();
    }
}
